<template>
	<view>
		<u-navbar :is-back="true" title="测试" title-size="30" height="50">
			<view style="margin-right: 30rpx;" slot="right" @click="navBack">
				<u-icon name="home-fill" color="#606266" size="35"></u-icon>
			</view>
		</u-navbar>
		
		
		<view style="margin-top: 200rpx;display: flex;justify-content: center;">
			
			<u-button plain size="medium" @click="getWechatAuthCode"> 授权</u-button>
			<u-button plain size="medium" @click="test">测试</u-button>
		</view>
		
	</view>
</template>

<script>
	import base from '@/config/baseUrl';
	import {isWeChat} from '@/utils/util.js';
	
	
	let that;
	export default {
		data(){
			return {
				code:''
			}
		},
		onLoad(opt) {
			// 通过链接 获取 code
			this.code = this.$http.getUrlParam('code');
			if(this.code){
				this.wechatAuth()
			}
		},
		beforeCreate() {
			that = this;
		},
		methods:{
			getWechatAuthCode(){
				if( !isWeChat() )  return uni.showToast({title:'当前不是微信浏览器'});
				// code 不存在进入此判断
				let _baseUrl = window.location.href;
				_baseUrl = encodeURIComponent(_baseUrl);
				let url =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${base.publicAppId}&redirect_uri=${_baseUrl}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
				// window.location.href = url;
				window.location.replace(url);
			},
			async wechatAuth(){
				const res = await this.$http.request({
					url: this.$api.default.wechatAuth,
					data: {code: this.code,}
				});
				if(res.code !== 0) return  uni.showToast({title:res.msg});
				
				if(!res.data.access_token) {
					let host =  window.location.protocol + '//' + window.location.host + window.location.pathname;
					window.location.href =  host + '#/pages/public/bind?openid=' + res.data.wechat_user.openid;
					return ;
				}
				
				// 否则保存 access_token 到缓存 跳转到上次的页面 或者个人页 跳转后删除 _login_pre_url 的缓存
				this.$http.setToken(res.data.access_token);
				let url = uni.getStorageSync('_login_pre_url') ? uni.getStorageSync('_login_pre_url') : '/pages/user/index';
				this.$http.setUserInfo();
					
				let host =  window.location.protocol + '//' + window.location.host + window.location.pathname;
				host = host.replace(/\/+$/gm,'');
				window.location.href =  host + '/#' + url;
			},
			doSomethingAsync(time = 1000) {
				return new Promise(resolve => setTimeout(resolve, time)); // 模拟异步操作
			},
			async test(){
				console.log(111111);
				await that.doSomethingAsync(3000);
				console.log(2222222);
			}
		}
	}
</script>

<style lang="scss">
</style>